package cn.rkylin.oms.warehouse.extAdjust.controller;

import cn.rkylin.core.controller.ApolloController;
import cn.rkylin.oms.common.annotation.SystemControllerLog;
import cn.rkylin.oms.common.context.CurrentUser;
import cn.rkylin.oms.common.context.WebContextFactory;
import cn.rkylin.oms.order.controller.OrderController;
import cn.rkylin.oms.warehouse.extAdjust.dao.AdjustDAOImpl;
import cn.rkylin.oms.warehouse.extAdjust.service.AdjustSkuService;
import cn.rkylin.oms.warehouse.extAdjust.vo.AdjustInfo;
import cn.rkylin.oms.warehouse.extAdjust.vo.AdjustSkuExportVO;
import cn.rkylin.oms.warehouse.extAdjust.vo.AdjustSkuVO;
import cn.rkylin.oms.warehouse.extAdjust.vo.AdjustVO;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.net.URLDecoder;
import java.util.List;
import java.util.Map;
import java.util.HashMap;

/**
 * Created by Administrator on 2018-4-16.
 */
@Controller
@RequestMapping("/extAdjust")
public class ExtAdjustController extends ApolloController {

    private static final Log logger = LogFactory.getLog(ExtAdjustController.class);
    private static final String PAGE_SELECT_STATEMENT = "pageSelectAdjust";

    @Autowired
    public AdjustSkuService adjustSkuService;
    /**
     * 取得tab页面头上的记录数
     * @param quickSearch
     * @param formVO
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getTabCounts")
    public Map<String, Object> getTabCounts(String quickSearch, @RequestBody AdjustVO formVO) throws Exception {
        logger.info(String.format("取得tab页面头上的记录数：/extAdjust/getTabCounts"));
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            // 查询条件
            AdjustVO param = new AdjustVO();

            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            if (currentUser == null) {
                returnMap.put(JSON_RESULT, FAILED);
                returnMap.put(JSON_MSG, "当前用户失效");
                return returnMap;
            }

            String prjId = currentUser.getCurrentProject().getPrjId();

            param.setPrjId(prjId);
            // 快速查询
            quickSearch = URLDecoder.decode(quickSearch, "UTF-8");
            quickSearch = quickSearch.trim();
            if (StringUtils.isNotBlank(quickSearch)) {
                param.setSearchCondition(quickSearch);
            }

            if (formVO != null) {

                if (formVO.getCreateTimeS()!=null){
                    param.setCreateTimeS(formVO.getCreateTimeS());
                }

                if (formVO.getCreateTimeE()!=null){
                    param.setCreateTimeE(formVO.getCreateTimeE());
                }

                if (StringUtils.isNotBlank(formVO.getStorId())){
                    param.setStorId(formVO.getStorId());
                }

                if (StringUtils.isNotBlank(formVO.getAdjustType())){
                    param.setAdjustType(formVO.getAdjustType());
                }
            }

            List<AdjustVO> list = adjustSkuService.findCounts(param);

            // 设置返回结果内容
            returnMap.put(JSON_RESULT, SUCCESS);
            int countWait = 0;
            int countComplete = 0;
            int countCancel = 0;

            if (list != null && list.size() > 0) {
                countWait = list.get(0).getCountWait() != null ? list.get(0).getCountWait().intValue() : 0;
                countComplete = list.get(0).getCountComplete() != null ? list.get(0).getCountComplete().intValue() : 0;
                countCancel = list.get(0).getCountCancel() != null ? list.get(0).getCountCancel().intValue() : 0;
            }
            returnMap.put("countWait", countWait);
            returnMap.put("countComplete", countComplete);
            returnMap.put("countCancel", countCancel);
        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }

    /**
     * 待调整
     *
     * @param quickSearch 快速查询条件
     * @param formJson    高级检索条件
     * @return 返回值JSON格式字符串
     * @throws Exception
     * @Param start 第几页
     * @Param length 每页多少行
     */
    @ResponseBody
    @RequestMapping(value = "/getWaitTable")
    public Map<String, Object> getWaitTable(String quickSearch, @RequestParam(required = false, defaultValue = "0") int start,
                                                  @RequestParam(required = false, defaultValue = "10") int length, String formJson) throws Exception {
        logger.info(String.format("待调整：/extAdjust/getWaitTable"));
        // 查询条件
        AdjustVO param = new AdjustVO();
        // 状态
        param.setAdjustStatus("n");
        param.setIsCancel("n");

        // 下面代码放到private方法中时，会获取到上一个请求中的currentUser，所以先移到这里。
        Map<String, Object> returnMap = new HashMap<String, Object>();
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        if (currentUser == null) {
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, "当前用户失效");
            return returnMap;
        }
        String prjId = currentUser.getCurrentProject().getPrjId();
        param.setPrjId(prjId);
        return getDataList(quickSearch, start, length, formJson, param);
    }

    /**
     * 已经调整
     *
     * @param quickSearch 快速查询条件
     * @param formJson    高级检索条件
     * @return 返回值JSON格式字符串
     * @throws Exception
     * @Param start 第几页
     * @Param length 每页多少行
     */
    @ResponseBody
    @RequestMapping(value = "/getCompleteTable")
    public Map<String, Object> getCompleteTable(String quickSearch, @RequestParam(required = false, defaultValue = "0") int start,
                                            @RequestParam(required = false, defaultValue = "10") int length, String formJson) throws Exception {
        logger.info(String.format("已经调整：/extAdjust/getCompleteTable"));
        // 查询条件
        AdjustVO param = new AdjustVO();
        // 状态
        param.setAdjustStatus("y");
        param.setIsCancel("n");

        // 下面代码放到private方法中时，会获取到上一个请求中的currentUser，所以先移到这里。
        Map<String, Object> returnMap = new HashMap<String, Object>();
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        if (currentUser == null) {
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, "当前用户失效");
            return returnMap;
        }
        String prjId = currentUser.getCurrentProject().getPrjId();
        param.setPrjId(prjId);
        return getDataList(quickSearch, start, length, formJson, param);
    }

    /**
     * 已经废弃
     *
     * @param quickSearch 快速查询条件
     * @param formJson    高级检索条件
     * @return 返回值JSON格式字符串
     * @throws Exception
     * @Param start 第几页
     * @Param length 每页多少行
     */
    @ResponseBody
    @RequestMapping(value = "/getCancelTable")
    public Map<String, Object> getCancelTable(String quickSearch, @RequestParam(required = false, defaultValue = "0") int start,
                                                @RequestParam(required = false, defaultValue = "10") int length, String formJson) throws Exception {
        logger.info(String.format("已经废弃：/extAdjust/getCancelTable"));
        // 查询条件
        AdjustVO param = new AdjustVO();
        // 状态
        param.setIsCancel("y");

        // 下面代码放到private方法中时，会获取到上一个请求中的currentUser，所以先移到这里。
        Map<String, Object> returnMap = new HashMap<String, Object>();
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        if (currentUser == null) {
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, "当前用户失效");
            return returnMap;
        }
        String prjId = currentUser.getCurrentProject().getPrjId();
        param.setPrjId(prjId);
        return getDataList(quickSearch, start, length, formJson, param);
    }

    /**
     * 根据不同的需求返回列表数据
     *
     * @param quickSearch
     * @param start
     * @param length
     * @param formJson
     * @return
     */
    private Map<String, Object> getDataList(String quickSearch, int start, int length, String formJson, AdjustVO param) {
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            // 处理分页
            if (length == -1) {
                length = Integer.MAX_VALUE;
            }
            int page = start / length + 1;

            // 快速查询
            quickSearch = URLDecoder.decode(quickSearch, "UTF-8");
            quickSearch = quickSearch.trim();
            if (StringUtils.isNotBlank(quickSearch)) {
                param.setSearchCondition(quickSearch);
            }

            // 高级查询检索条件
            formJson = URLDecoder.decode(formJson, "UTF-8");
            // json转换成为ＶＯ
            AdjustVO formVO = JSONObject.parseObject(formJson, AdjustVO.class);
            if (formVO != null) {
                if (formVO.getCreateTimeS()!=null){
                    param.setCreateTimeS(formVO.getCreateTimeS());
                }

                if (formVO.getCreateTimeE()!=null){
                    param.setCreateTimeE(formVO.getCreateTimeE());
                }

                if (StringUtils.isNotBlank(formVO.getStorId())){
                    param.setStorId(formVO.getStorId());
                }

                if (StringUtils.isNotBlank(formVO.getAdjustType())){
                    param.setAdjustType(formVO.getAdjustType());
                }
            }

            // 处理转义的字段
            Map<String, String> replaceFieldsMap = new HashMap<String, String>();
            replaceFieldsMap.put("adjustTypeName", "a.adjust_type");

            // 排序语句生成
            String orderStatement = getOrderString(AdjustDAOImpl.class.getName(), PAGE_SELECT_STATEMENT, replaceFieldsMap);
            if (StringUtils.isNotEmpty(orderStatement)) {
                param.setOrderBy(orderStatement);
            }

            // 获取分页数据
            AdjustVO vo = new AdjustVO();
            PageInfo<AdjustVO> adjustVOList = adjustSkuService.findByWhere(page, length, param);


            // 设置返回结果内容
            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(RECORDS_FILTERED, adjustVOList.getTotal());
            returnMap.put(RECORDS_TOTAL, adjustVOList.getTotal());
            returnMap.put(RETURN_DATA, adjustVOList.getList());

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }

    /**
     * 调整单数据处理
     *
     * @param adjustInfo
     */
    @ResponseBody
    @RequestMapping(value = "/createAdjust")
    public Map<String, Object> createAdjust(@RequestBody AdjustInfo adjustInfo) throws Exception {
        logger.info(String.format("调整单数据处理：/extAdjust/createAdjust：" + JSON.toJSONString(adjustInfo)));

// 用于返回值的json对象
        Map<String, Object> resultMap = new HashMap<String, Object>();
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        if (currentUser == null) {
            resultMap.put(JSON_RESULT, FAILED);
            resultMap.put(JSON_MSG, "当前用户失效");
            return resultMap;
        }
        Map<String, String> mapParm = new HashMap<String, String>();
        Map<String, String> enterpriseMap = currentUser.getEnterpriseMap();
        if (enterpriseMap == null || enterpriseMap.size() == 0) {
            resultMap.put(JSON_RESULT, FAILED);
            resultMap.put(JSON_MSG, "当前用户没有企业ID");
            return resultMap;
        }
        String entId = "";
        String entName = "";
        for (Map.Entry<String, String> entry : enterpriseMap.entrySet()) {
            entId = entry.getKey();
            entName = entry.getValue();
        }

        adjustInfo.setCreateUser(currentUser.getAccount());
        adjustInfo.setEntId(entId);
        adjustInfo.setPrjId(currentUser.getCurrentProject().getPrjId());
        adjustInfo.setPrjShortName(currentUser.getCurrentProject().getPrjShortName());

        Map<String, Object> map = adjustSkuService.modifyAdjustData(adjustInfo);

        resultMap.put(JSON_RESULT, map.get(JSON_RESULT));
        resultMap.put(JSON_MSG, map.get(JSON_MSG));
        return resultMap;

    }

    /**
     * 取得orderInfo
     *
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getAdjustInfo", method = RequestMethod.GET)
    public Map<String, Object> getAdjustInfo(String adjustId) throws Exception {
        logger.info(String.format("调整单数据检索：/extAdjust/getAdjustInfo"));
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            // 用于返回值的json对象
            Map<String, Object> resultMap = new HashMap<String, Object>();

            // orderId如果是空就返回错误信息
            if (StringUtils.isBlank(adjustId)) {
                resultMap.put(JSON_RESULT, FAILED);
                resultMap.put(JSON_MSG, "adjustId是空");
                return resultMap;
            }

            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            if (currentUser == null) {
                resultMap.put(JSON_RESULT, FAILED);
                resultMap.put(JSON_MSG, "当前用户失效");
                return resultMap;
            }

            AdjustVO param = new AdjustVO();
            param.setAdjustId(adjustId);

            // 获取分页数据
            PageInfo<AdjustVO> adjustVOList = adjustSkuService.findByWhere(0, Integer.MAX_VALUE, param);
            if (adjustVOList != null && adjustVOList.getList().size() > 0) {
                returnMap.put(JSON_RESULT, SUCCESS);
                returnMap.put(RETURN_DATA, adjustVOList.getList().get(0));
            } else {
                returnMap.put(JSON_RESULT, FAILED);
                resultMap.put(JSON_MSG, "adjustId是" + adjustId + "的数据不存在");
                returnMap.put(RETURN_DATA, null);
            }
            // 设置返回结果内容

        } catch (Exception ex) {
            logger.error(ex.getMessage(), ex);
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        // 生成返回结果json串，null内容也需要返回
        return returnMap;
    }

    /**
     * orderSkuLIst
     *
     * @param adjustId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/getAdjustSku")
    public Map<String, Object> getAdjustSku(String adjustId) throws Exception {
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();

        // 取得规格
        AdjustSkuVO adjustSkuVO = new AdjustSkuVO();
        adjustSkuVO.setAdjustId(adjustId);

        List<AdjustSkuVO> arrSku = StringUtils.isBlank(adjustId) ? null : adjustSkuService.getAdjustSku(adjustSkuVO);

        returnMap.put("data", arrSku);
        returnMap.put(JSON_RESULT, SUCCESS);

        return returnMap;
    }

    /**
     * orderSkuLIst
     *
     * @param adjustId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/showAdjustSku")
    public Map<String, Object> showAdjustSku(String adjustId) throws Exception {
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();

        // 取得规格
        AdjustSkuVO adjustSkuVO = new AdjustSkuVO();
        adjustSkuVO.setAdjustId(adjustId);

        List<AdjustSkuVO> arrSku = StringUtils.isBlank(adjustId) ? null : adjustSkuService.showAdjustSku(adjustSkuVO);

        returnMap.put("data", arrSku);
        returnMap.put(JSON_RESULT, SUCCESS);

        return returnMap;
    }


    /**
     * 调整
     *
     * @param adjustId 系统订单id
     */
    @ResponseBody
    @RequestMapping(value = "/doAdjust")
    @SystemControllerLog(module = "调整单", operation = "调整", keyCode = "adjustId")
    public Map<String, Object> doAdjust(String adjustId) {
        logger.info(String.format("调整：/extAdjust/doAdjust"));
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        if (currentUser == null) {
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, "当前用户失效");
            return returnMap;
        }
        Map<String, String> mapParm = new HashMap<String, String>();
        Map<String, String> enterpriseMap = currentUser.getEnterpriseMap();
        if (enterpriseMap == null || enterpriseMap.size() == 0) {
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, "当前用户没有企业ID");
            return returnMap;
        }
        try {
            Map<String, Object> serviceMap = adjustSkuService.updateAdjust(adjustId,currentUser.getFullName());
            returnMap.put(JSON_RESULT, serviceMap.get(JSON_RESULT));
            returnMap.put(JSON_MSG, serviceMap.get(JSON_MSG));
        } catch (Exception ex) {
            ex.printStackTrace();
            logger.error(String.format("调整：/extAdjust/doAdjust")+ex.getMessage());
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        return returnMap;
    }

    /**
     * 废弃
     *
     * @param adjustId
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/adjustCancel")
    @SystemControllerLog(module = "调整单", operation = "废弃", keyCode = "adjustId")
    public Map<String, Object> adjustCancel(String adjustId) throws Exception {
        // 用于返回值的json对象
        Map<String, Object> returnMap = new HashMap<String, Object>();
        try {
            int count = adjustSkuService.batchCancelAdjust(adjustId.split(","));
            returnMap.put(JSON_RESULT, SUCCESS);
            returnMap.put(JSON_MSG, "废弃处理成功");
        } catch (Exception ex) {
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, ex.getMessage());
        }
        return returnMap;
    }

    /**
     * 验证需要导出的条件
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/exportCheckAdjust")
    public Map<String, Object> exportCheckAdjust() throws Exception {
        logger.info("调整单导出check：/extAdjust/exportCheckAdjust");
        Map<String, Object> returnJSON = new HashMap<String, Object>();
        try {

            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            if (currentUser == null){
                returnJSON.put(JSON_RESULT, FAILED);
                returnJSON.put(JSON_MSG, "查询当前登录人失败");
                return returnJSON;
            }

            // 获取当前登录人所属项目
            String projectId = currentUser.getCurrentProject().getPrjId();
            if (StringUtils.isBlank(projectId) || currentUser.getProjectMap() == null || currentUser.getProjectMap().size() <= 0) {
                returnJSON.put(JSON_RESULT, FAILED);
                returnJSON.put(JSON_MSG, "查询当前登录人所属项目失败");
                return returnJSON;
            }

            // 上述check都没有错误的场合
            if (returnJSON.get(JSON_RESULT) == null) {
                returnJSON.put(JSON_RESULT, SUCCESS);
            }

        } catch (Exception ex){
            returnJSON.put(JSON_RESULT, FAILED);
            returnJSON.put(JSON_MSG, ex.getMessage());
        }
        return returnJSON;
    }
    /**
     * 导出
     * @param colName
     * @param colValue
     * @param quickSearch
     * @return
     * @throws Exception
     */
    @ResponseBody
    @RequestMapping(value = "/exportAdjust")
    public String exportAdjust(String colName, String colValue, String quickSearch, String exportType,String exportSearchCondition) throws Exception {
        logger.info("系统订单信息导出：/extAdjust/exportAdjust");
        try {
            // 查询条件
            Map param = new HashMap<String,Object>();

            // 下面代码放到private方法中时，会获取到上一个请求中的currentUser，所以先移到这里。
            Map<String, Object> returnMap = new HashMap<String, Object>();
            CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
            if (currentUser == null) {
                logger.error("系统订单信息导出：/extAdjust/exportAdjust,查询当前登录人失败");
                return null;
            }

            String prjId = currentUser.getCurrentProject().getPrjId();
            param.put("prjId",prjId);

            if (StringUtils.isNotBlank(quickSearch)) {
                param.put("searchCondition",URLDecoder.decode(quickSearch, "UTF-8"));
            }

            colName= URLDecoder.decode(colName, "UTF-8");
            colValue= URLDecoder.decode(colValue, "UTF-8");
            // 高级查询检索条件
            exportSearchCondition = URLDecoder.decode(exportSearchCondition, "UTF-8");
            // json转换成为ＶＯ
            AdjustVO formVO = JSONObject.parseObject(exportSearchCondition, AdjustVO.class);
            if (formVO != null) {
                if (formVO.getCreateTimeS()!=null){
                    param.put("createTimeS",formVO.getCreateTimeS());
                }

                if (formVO.getCreateTimeE()!=null){
                    param.put("createTimeE",formVO.getCreateTimeE());
                }

                if (StringUtils.isNotBlank(formVO.getStorId())){
                    param.put("storId",formVO.getStorId());
                }

                if (StringUtils.isNotBlank(formVO.getAdjustType())){
                    param.put("adjustType",formVO.getAdjustType());
                }
            }

            List<AdjustSkuExportVO> adjustExportList = adjustSkuService.exportSku(param);
            exportExcelFile(adjustExportList,colName,colValue,"调整单导出");

        } catch (Exception ex){
            ex.printStackTrace();
            logger.error(ex.getMessage());
        }
        return null;
    }

    @ResponseBody
    @RequestMapping(value = "/importFile")
    public Map<String, Object> importFile(String json, String storIdNew, String mapAdjustSku) throws Exception {
        logger.info(String.format("导入调整单：/extAdjust/importFile:storId:"+storIdNew+"JSON:"+json));
        Map<String, Object> returnMap = new HashMap<String, Object>();

        CurrentUser currentUser = WebContextFactory.getWebContext().getCurrentUser();
        if (currentUser == null) {
            logger.error("系统订单信息导出：/extAdjust/exportAdjust,查询当前登录人失败");
            return null;
        }
        Map<String, String> enterpriseMap = currentUser.getEnterpriseMap();
        if (enterpriseMap == null || enterpriseMap.size() == 0) {
            returnMap.put(JSON_RESULT, FAILED);
            returnMap.put(JSON_MSG, "当前用户没有企业ID");
            return returnMap;
        }
        String entId = "";
        String entName = "";
        for (Map.Entry<String, String> entry : enterpriseMap.entrySet()) {
            entId = entry.getKey();
            entName = entry.getValue();
        }

        String prjId = currentUser.getCurrentProject().getPrjId();

        Map<String,String> map = new HashMap<String,String>();
        map.put("json",json);
        map.put("storId",storIdNew);
        map.put("prjId",prjId);
        map.put("entId",entId);
        map.put("mapAdjustSku",mapAdjustSku);
        logger.info(String.format("导入调整单：/extAdjust/importFile:storId:"+storIdNew+" prjId:"+prjId+" entId:"+entId+" JSON:"+json));
        return adjustSkuService.importCheck(map);
    }
}


